import { parseTime, currentBrower } from '@/utils'
import { Message, Loading } from 'element-ui'
import { exportExcel } from '@/api/export'

export function exportExcelFun(url, params, fileName) {
  const loading = Loading.service({
    lock: true,
    text: '导出中...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  exportExcel(url, params).then(file => {
    console.log(file)
    // res 二进制
    var blob = new Blob([file], {
      type:
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'
    }) // application/
    var downloadElement = document.createElement('a')
    var href = window.URL.createObjectURL(blob) // 创建下载的链接
    try {
      if (currentBrower() === 'IE') {
        window.navigator.msSaveBlob(blob, `${fileName}.xls`)
        loading.close()
      } else {
        downloadElement.href = href
        downloadElement.download = `${fileName}.xls`
        document.body.appendChild(downloadElement)
        downloadElement.click()
        document.body.removeChild(downloadElement)
        window.URL.revokeObjectURL(href)
        loading.close()
      }
    } catch (e) {
      console.log(e, 'error export')
      loading.close()
    }
  })
}

/**
 * 时间区间范围
 */
export function timeRange(time, limtiDay = 30, message = '') {
  if (time && time.length > 1) {
    const startdate = parseTime(time[0])
    const orderEndTime = parseTime(time[1])
    const startD = new Date(Date.parse(startdate.replace(/-/g, '/')))
    const endD = new Date(Date.parse(orderEndTime.replace(/-/g, '/')))
    const days = parseInt(
      (endD.getTime() - startD.getTime()) / (1000 * 60 * 60 * 24)
    )
    if (days > limtiDay) {
      Message({
        message: message || '处理时间需控制在30天之内~',
        type: 'warning'
      })
      return false
    } else {
      return true
    }
  } else {
    Message({
      message: '请选择处理时间',
      type: 'warning'
    })
    return false
  }
}
